package lib.quasar.widget.emoji;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import lib.quasar.context.BaseApp;
import lib.quasar.util.DimenUtil;
import lib.quasar.util.InputUtil;
import lib.quasar.util.LogUtil;
import lib.quasar.widget.R;
import lib.quasar.widget.line.LineLinearLayout;

/**
 * description: 监听键盘弹起关闭
 * created by kalu on 2018/6/13 17:21
 */
public final class EmojiLayout extends LinearLayout {

    // 表情按钮
    private final ImageView imageEmoji = new ImageView(getContext().getApplicationContext());
    // 发送按钮, 代替三种状态(弹起键盘, 收起键盘, 显示菜单)
    private final ImageView imageSend = new ImageView(getContext().getApplicationContext());
    // 输入框
    private final EditText editInput = new EditText(getContext().getApplicationContext());
    // 底部菜单
    private final LineLinearLayout menuLayout = new LineLinearLayout(getContext().getApplicationContext());
    // 菜单列表
    private final RecyclerView menuRecycler = new RecyclerView(getContext().getApplicationContext());

    private int maxHeight = 0, minHeight = 0, measuredHeight = 0;

    public EmojiLayout(Context context) {
        super(context);
    }

    public EmojiLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EmojiLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        if (null == mOnInputChangeListener)
            return;

        final int newMeasuredHeight = getMeasuredHeight();

        if (minHeight == 0) {
            minHeight = newMeasuredHeight;
        }
        if (maxHeight == 0) {
            maxHeight = newMeasuredHeight;
        }

        maxHeight = Math.max(newMeasuredHeight, maxHeight);
        minHeight = Math.min(newMeasuredHeight, minHeight);
        if (minHeight == maxHeight)
            return;

        if (newMeasuredHeight < maxHeight) {

            if (measuredHeight != newMeasuredHeight) {
                mOnInputChangeListener.onInputOpen(maxHeight, minHeight);
                measuredHeight = newMeasuredHeight;

                LogUtil.e("key_open", "键盘弹出 ==> childcount = " + getChildCount());
                if (getChildCount() == 3) {
                    menuRecycler.setTag(maxHeight - minHeight);
                } else {
                    editInput.requestFocus();
                    // 改变图片
                    imageSend.setTag(R.drawable.ic_chat_open);
                    imageSend.setImageResource(R.drawable.ic_chat_open);
                    // 菜单高度
                    menuRecycler.setTag(maxHeight - minHeight);
                    final LayoutParams layoutParams = (LayoutParams) menuRecycler.getLayoutParams();
                    layoutParams.height = 0;
                    final RecyclerView.Adapter adapter = menuRecycler.getAdapter();
                    if (null != adapter) {
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        } else {

            if (measuredHeight != newMeasuredHeight) {

                LogUtil.e("key_open", "键盘关闭 ==> childcount = " + getChildCount());
                mOnInputChangeListener.onInputShut(maxHeight, minHeight);
                measuredHeight = newMeasuredHeight;

                if (getChildCount() == 3) {
                    LayoutParams parmars = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, maxHeight - minHeight);
                    menuRecycler.setLayoutParams(parmars);
                    menuRecycler.setTag(maxHeight - minHeight);
                    menuRecycler.setBackgroundColor(Color.WHITE);
                    addView(menuRecycler);
                    if (null != mOnInputChangeListener) {
                        mOnInputChangeListener.onMenuLayout(menuRecycler);
                    }
                } else {
                    // 改变图片
                    imageSend.setTag(R.drawable.ic_chat_menu_down);
                    imageSend.setImageResource(R.drawable.ic_chat_menu_down);
                    // 清除焦点
                    editInput.clearFocus();
                    // 菜单高度
                    if (null == menuRecycler.getTag()) return;
                    // 刷新菜单视图
                    menuRecycler.getLayoutParams().height = (int) menuRecycler.getTag();
                    final RecyclerView.Adapter adapter = menuRecycler.getAdapter();
                    if (null != adapter) {
                        adapter.notifyDataSetChanged();
                    }
                    if (null != mOnInputChangeListener) {
                        mOnInputChangeListener.onMenuSwitch(menuRecycler);
                    }
                }
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        final DisplayMetrics metrics = getContext().getApplicationContext().getResources().getDisplayMetrics();
        final int menuHeight = (int) (50 * metrics.density);
        final int childHeight = (int) (30 * metrics.density);
        final int margin = (int) (10 * metrics.density);
        // step1
        final LayoutParams params1 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, menuHeight);
        params1.gravity = Gravity.BOTTOM;
        menuLayout.setPadding(margin, 0, margin, 0);
        menuLayout.setLayoutParams(params1);
        menuLayout.setGravity(Gravity.CENTER_VERTICAL);
        menuLayout.setLineColor(BaseApp.getColors(R.color.color_line_gray));
        menuLayout.setLineHeight(DimenUtil.sp2px(1));
        menuLayout.setBackgroundColor(Color.WHITE);
        menuLayout.setLocationLine(true, true, false, false);
        addView(menuLayout);
        // step2
        final LayoutParams params2 = new LayoutParams(childHeight, childHeight);
        imageEmoji.setLayoutParams(params2);
        imageEmoji.setImageResource(R.drawable.ic_chat_emoji);
        menuLayout.addView(imageEmoji);
        // step3
        final LayoutParams params3 = new LayoutParams(0, menuHeight);
        params3.setMargins(margin, 0, margin, 0);
        params3.weight = 1;
        editInput.setSingleLine(true);
        editInput.setHint("输入聊天信息");
        editInput.setLayoutParams(params3);
        editInput.setBackgroundDrawable(null);
        menuLayout.addView(editInput);
        // step4
        final LayoutParams params4 = new LayoutParams(childHeight, childHeight);
        imageSend.setLayoutParams(params4);
        imageSend.setImageResource(R.drawable.ic_chat_menu_up);
        menuLayout.addView(imageSend);
        // step5
        imageSend.setOnClickListener(v -> {
            //  LogUtil.e("key_open", "键盘隐藏, 菜单隐藏, 显示弹起图标")
            if (null == imageSend.getTag() || (int) imageSend.getTag() == R.drawable.ic_chat_menu_up) {
                // 改变图片
                imageSend.setTag(R.drawable.ic_chat_open);
                imageSend.setImageResource(R.drawable.ic_chat_open);
                // 弹起键盘
                toogleKeybord();
                LogUtil.e("key_open", "键盘隐藏, 菜单隐藏, 显示弹起图标");
            }
            // LogUtil.e("key_open", "键盘显示, 菜单显示, 显示发送图标")
            else if ((int) imageSend.getTag() == R.drawable.ic_chat_send) {
                if (null != mOnInputChangeListener) {
                    final Editable editable = editInput.getText();
                    final String str = editable.toString();
                    if (!TextUtils.isEmpty(str)) {
                        mOnInputChangeListener.onMenuSend(str);
                        editable.clear();
                    }
                }
                LogUtil.e("key_open", "键盘显示, 菜单显示, 显示发送图标");
            }
            // LogUtil.e("key_open", "键盘显示, 菜单显示, 显示更多图标")
            else if ((int) imageSend.getTag() == R.drawable.ic_chat_open) {
                imageSend.setTag(R.drawable.ic_chat_menu_down);
                imageSend.setImageResource(R.drawable.ic_chat_menu_down);
                toogleKeybord();
                LogUtil.e("key_open", "键盘显示, 菜单显示, 显示更多图标");
            }
            // LogUtil.e("key_open", "键盘隐藏, 菜单显示, 显示收起图标")
            else if ((int) imageSend.getTag() == R.drawable.ic_chat_menu_down) {
                imageSend.setTag(R.drawable.ic_chat_menu_up);
                imageSend.setImageResource(R.drawable.ic_chat_menu_up);
                // 菜单高度
                if (null == menuRecycler.getTag()) return;
                final LayoutParams layoutParams = (LayoutParams) menuRecycler.getLayoutParams();
                layoutParams.height = 0;
                final RecyclerView.Adapter adapter = menuRecycler.getAdapter();
                if (null != adapter) {
                    adapter.notifyDataSetChanged();
                }
                LogUtil.e("key_open", "键盘隐藏, 菜单显示, 显示收起图标");
            }
        });
        // step6
        imageEmoji.setOnClickListener(v -> Toast.makeText(getContext(), "表情", Toast.LENGTH_SHORT).show());
        // step7
        editInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null != s && !s.toString().isEmpty()) {
                    imageSend.setTag(R.drawable.ic_chat_send);
                    imageSend.setImageResource(R.drawable.ic_chat_send);
                } else {
                    imageSend.setTag(R.drawable.ic_chat_open);
                    imageSend.setImageResource(R.drawable.ic_chat_open);
                }
            }
        });
        // step8
        editInput.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                imageSend.setTag(R.drawable.ic_chat_open);
                imageSend.setImageResource(R.drawable.ic_chat_open);
            }
        });
    }

    private final void toogleKeybord() {
        final InputMethodManager imm = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public final void closeMenu() {

        final RecyclerView.Adapter adapter = menuRecycler.getAdapter();
        if (null == adapter) {
            InputUtil.closeKeybord(editInput);
            return;
        }

        if (null == menuRecycler.getTag()) {
            InputUtil.closeKeybord(editInput);
            return;
        }

        final LayoutParams layoutParams = (LayoutParams) menuRecycler.getLayoutParams();
        if (null == layoutParams) {
            InputUtil.closeKeybord(editInput);
            return;
        }

        layoutParams.height = 0;
        adapter.notifyDataSetChanged();
        imageSend.setTag(R.drawable.ic_chat_menu_up);
        imageSend.setImageResource(R.drawable.ic_chat_menu_up);
        InputUtil.closeKeybord(editInput);
    }

    /**********************************************************************************************/

    private OnInputChangeListener mOnInputChangeListener;

    public void setOnInputChangeListener(OnInputChangeListener mOnInputChangeListener) {
        this.mOnInputChangeListener = mOnInputChangeListener;
    }

    public interface OnInputChangeListener {

        default void onInputOpen(int maxHeight, int minHeight) {
        }

        default void onInputShut(int maxHeight, int minHeight) {
        }

        void onMenuLayout(RecyclerView recycler);

        void onMenuSwitch(RecyclerView recycler);

        void onMenuSend(String str);
    }
}